package client;

import lovedna.math.Vector4;
import lovedna.format.mesh.GeometryBuffers;
import lovedna.ds.BufferVector4;
import lovedna.game.geometry.GeomSphere;
import lovedna.game.Mesh;
import lovedna.graphics.CullMode;
import lovedna.game.materials.RenderQueue;
import lovedna.utils.macro.CompileTime;
import lovedna.game.materials.ShaderSource;
import lovedna.game.components.MeshRenderer;
import lovedna.math.Vector3;
import lovedna.game.Actor;

class Shadow extends Actor {
    private var _shadow:GeometryBuffers;
    private var _v4:Vector4;
    private var _count:Int;
    private var _mesh:Mesh;
    private var _mr:MeshRenderer;
    public function new() {
        super();
        new ShaderSource("shadows", CompileTime.readFile("resource/shaders/shadows.glsl"));
        this.transform.scale.set(1, 0.2, 1);
        _v4=new Vector4();
        var mr:MeshRenderer = this.addComponent(MeshRenderer);
        _mr=mr;
        _mr.material.renderQueue=RenderQueue.Background;
		mr.material.loadShader("shadows");
		mr.material.renderState.cullMode = CullMode.off;
		_mesh = new Mesh();
        mr.mesh=_mesh;
        var shadow = new GeomSphere();
        _shadow=shadow;
        shadow.radius = 1.0;
        shadow.color2 = new BufferVector4();
        _shadow.color2.instanceDivisor=1;
        _mesh.fromBuffer(shadow.build());
        _count=0;
        _mr.visible=false;
        // clear();
        // for(i in 0...10){
        //     addShadows(new Vector3(i,0,i),0);
        // }
        // complete();

    }
    public function clear() {
        _shadow.color2.clear();
        _count=0;
    }
    public function addShadows(pos:Vector3,size:Float) {
        _v4.set(pos.x,pos.y,pos.z,size);
        _shadow.color2.push(_v4);
        _count++;
    }
    public function complete() {
        _mr.visible=_count>0;
        if(!_mr.visible)return;
        _mesh.gpuBuffer.indexBuffer.instancedCount = _count;
        _shadow.update();
        
    }
}
